<?php
/**
 * 整体妆容表
 *
 * @author Lyun
 * @date 2018/6/13
 * @copyright PanxSoft Inc.
 */
namespace App\Models\Store;

use App\Models\Concerns\ScopeFilterable;
use App\Models\Customer\Asset;
use App\Models\Customer\PackAssetPivotProduct;
use App\Models\Panx\Product;
use App\Services\Utils\Bosable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * @property int $id
 * @property string $name
 * @property string thumb
 * @property int priority
 * @property int is_deleted
 * @property int src_pack_id
 *
 * @property-read PackCategory $packCategory
 * @property-read Collection|Asset[] assets
 * @property-read Collection|PackAssetPivotProduct[] $assetProductPivots
 *
 * @method static self filterIsDeleted($is_deleted)
 * @method static self filterPackCategoryId($pack_category_id)
 *
 * @mixin Builder
 */
class Pack extends Model
{
    use Bosable, ScopeFilterable;

    const IS_NO_DELETED = 0;  // 使用中

    const IS_DELETED = 1;     // 已下架

    const STORE_ID_CUSTOMER = 0; // 店铺 ID 为 0 ，代表为客户设置的整妆

    const PACK_CATEGORY_NULL_ID = 0; // 无分类ID

    protected $thumb_bos_key_prefix = 'Makeup_Img/';

    protected $table = 'packs';

    protected $guarded = [];

    public $bos_columns = ['thumb'];

    protected $casts = [
        'src_pack_id' => 'int',
        'priority'    => 'int',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function assets()
    {
        return $this
            ->belongsToMany(
                Asset::class, 'pack_pivot_asset', 'pack_id', 'asset_id'
            )
            ->withPivot(['index']);
    }

    /**
     * @return $this|\Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function assetProductPivots()
    {
        return $this->hasMany(PackAssetPivotProduct::class, 'pack_id', 'id');
    }

    public function packAsset()
    {
        return $this->belongsTo(PackAsset::class, 'index', 'id');
    }

    public function packCategory()
    {
        return $this->belongsTo(PackCategory::class, 'pack_category_id', 'id');
    }

    public function sharePacks()
    {
        return $this->hasMany(Pack::class, 'src_pack_id', 'id');
    }


    /**
     * @param $thumb
     * @throws \Exception
     */
    public function setThumbAttribute($thumb)
    {
        if (is_file($thumb)) {
            $this->attributes['thumb'] = $this->uploadPostFile($thumb, $this->thumb_bos_key_prefix,
                true, 'png'
            );
        }else{
            $this->attributes['thumb'] = $thumb;
        }
    }

    /**
     * @param int $amount
     * @param array $extra
     * @return int
     */
    public function incrementRefCount(int $amount = 1, array $extra = []): int
    {
        return $this->increment('ref_count', $amount , $extra);
    }

    /**
     * @return mixed|null
     */
    public function getThumbAttribute()
    {
        if (!$this->attributes['thumb']) return null;

        return $this->getStaticUrl($this->attributes['thumb']);
    }

    /**
     * @used-by filterIsDeleted
     * @param Builder $query
     * @param $is_deleted
     * @return Builder
     */
    public function scopeFilterIsDeleted(Builder $query, $is_deleted)
    {
        if (! isset($is_deleted)) return $query;

        return $query->where('is_deleted', $is_deleted);
    }

    /**
     * @used-by filterPackCategoryId
     * @param Builder $query
     * @param $pack_category_id
     * @return Builder
     */
    public function scopeFilterPackCategoryId(Builder $query, $pack_category_id)
    {
        if (! $pack_category_id) return $query;

        return $query->where('pack_category_id', $pack_category_id);
    }

    /**
     * @deprecated - ??
     *
     * @return mixed|Collection
     */
    public function pivotProducts()
    {
        $asset_ids = DB::table('pack_pivot_asset')->where('pack_id', $this->id)->pluck('asset_id');

        $product_ids = DB::table('pack_asset_pivot_product')->whereIn('asset_id', $asset_ids)->pluck('product_id');

        return Product::whereIn('id', $product_ids)->with(['asset','thumbImage'])->get();
    }

    /**
     * 注册删除 bosKey 事件绑定
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * 监听bos清理事件
         *
         * @link https://coding.net/u/zeon/p/beauty-mirror/task/3803123 - #656 模型组要求不清理
         */
//        self::observe(BosCleanObserver::class);
    }

}
